package BarCode

import (
	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/code128"
	"go-barcode/internal/api"
	"image/png"
	"os"
)

type BarCode struct {
}

func (br *BarCode) Create(savePath, code string, img api.ImageCode) error {
	// 创建一个code128编码的 BarcodeIntCS
	cs, err := code128.Encode(code)
	if err != nil {
		return err
	}
	// 创建一个要输出数据的文件
	file, err := os.Create(savePath)
	defer func() {
		_ = file.Close()
	}()
	if err != nil {
		return err
	}
	w := img.Size.Width
	h := img.Size.Height
	if w <= 0 {
		w = 256
	}
	if h <= 0 {
		h = 64
	}
	// 设置图片像素大小
	qrCode, err := barcode.Scale(cs, w, h)

	if err != nil {
		return err
	}
	// 将code128的条形码编码为png图片
	err = png.Encode(file, qrCode)
	return err
}
